﻿using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleMinio;

public static class ImageTools
{
    /// <summary>
    /// 压缩图片
    /// </summary>
    /// <param name="source">原文件位置</param>
    /// <param name="target">生成目标文件位置</param>
    /// <param name="maxWidth">最大宽度，根据此宽度计算是否需要缩放，计算新高度</param>
    /// <param name="quality">图片质量，范围0-100</param>
    public static void Compress(string source, string target, decimal maxWidth, int quality)
    {
        using var file = File.OpenRead(source);
        using var fileStream = new SKManagedStream(file);
        using var bitmap = SKBitmap.Decode(fileStream);
        var width = (decimal)bitmap.Width;
        var height = (decimal)bitmap.Height;
        var newWidth = width;
        var newHeight = height;
        if (width > maxWidth && maxWidth != 0)
        {
            // 计算缩放比例
            var scale = maxWidth / width;

            // 计算缩放后的尺寸
            newWidth = maxWidth;
            newHeight = height * scale;
        }

        using var resized = bitmap.Resize(new SKImageInfo((int)newWidth, (int)newHeight), SKFilterQuality.Medium);
        if (resized != null)
        {
            using var image = SKImage.FromBitmap(resized);
            using var writeStream = File.OpenWrite(target);
            image.Encode(SKEncodedImageFormat.Jpeg, quality).SaveTo(writeStream);
        }
    }

    private static HttpClient HttpClient = new();

    public static Stream CompressToMemoryFromWeb(string filePath, int maxWidth, int quality)
    {
        if (string.IsNullOrWhiteSpace(filePath))
        {
            return null;
        }

        Console.WriteLine($"文件路径：{filePath}");

        // filePath = filePath.Replace("scqingrun.com", "192.168.1.222").Replace("183.222.63.159", "192.168.1.222");

        Console.WriteLine($"文件路径：{filePath}");


        var stream = new MemoryStream();

        try
        {
            var fileStream = HttpClient.GetStreamAsync(filePath).Result;

            using var bitmap = SKBitmap.Decode(fileStream);
            var width = bitmap.Width;
            var height = bitmap.Height;
            decimal newWidth = width;
            decimal newHeight = height;
            if (width > maxWidth && maxWidth != 0)
            {
                // 计算缩放比例
                var scale = (decimal)maxWidth / width;

                // 计算缩放后的尺寸
                newWidth = maxWidth;
                newHeight = height * scale;
            }

            using var resized =
                bitmap.Resize(new SKImageInfo((int)newWidth, (int)newHeight), SKFilterQuality.Medium);

            if (resized != null)
            {
                resized.Encode(SKEncodedImageFormat.Jpeg, quality)
                    .SaveTo(stream);

                stream.Position = 0;
            }
        }
        catch (Exception e)
        {
            throw new Exception(e.ToString());
        }

        return stream;
    }

    public static Stream CompressToMemoryFromWeb(Stream fileStream, int maxWidth, int quality, out decimal width, out decimal height)
    {
        using var bitmap = SKBitmap.Decode(fileStream);
        width = bitmap.Width;
        height = bitmap.Height;
        var newWidth = width;
        var newHeight = height;
        if (width > maxWidth && maxWidth != 0)
        {
            // 计算缩放比例
            var scale = maxWidth / width;

            // 计算缩放后的尺寸
            newWidth = maxWidth;
            newHeight = height * scale;
        }


        using var resized = bitmap.Resize(new SKImageInfo((int)newWidth, (int)newHeight), SKFilterQuality.Medium);
        var stream = new MemoryStream();
        if (resized != null)
        {
            resized.Encode(SKEncodedImageFormat.Jpeg, quality)
                .SaveTo(stream);

            stream.Position = 0;
        }

        return stream;
    }

    public static string ImageExtJudgment(string filePath, out string fileName, out string extension)
    {
        if (string.IsNullOrWhiteSpace(filePath))
        {
            fileName = "";
            extension = "";
            return "";
        }

        var ext = Path.GetExtension(filePath).ToLowerInvariant();
        if (ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".gif" || ext == ".bmp")
        {
            extension = ext;
            fileName = Path.GetFileName(filePath);
            return filePath;
        }

        extension = "";
        fileName = "";
        return "";
    }

}
